package com.wp.backup.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * MySQL备份还原工具类
 *
 * @author wp
 * @create 2019-03-06 10:33
 */
public class MySqlBackupRestoreUtils {

    /**
     * 备份数据库
     *
     * @param host             host地址
     * @param userName         数据库用户名
     * @param password         数据库密码
     * @param backupFolderPath 备份的路径
     * @param fileName         备份的文件名
     * @param databases        需要备份的数据库名称
     * @return
     * @throws Exception
     */
    public static boolean backup(String host, String userName, String password, String backupFolderPath, String fileName, List<String> databases) throws Exception {
        File backupFolderFile = new File(backupFolderPath);
        if (!backupFolderFile.exists()) {
            // 不存在则创建
            backupFolderFile.mkdirs();
        }
        if (!backupFolderPath.endsWith(File.separator) || !backupFolderPath.endsWith("/")) {
            backupFolderPath = backupFolderPath + File.separator;
        }
        // 拼接命令
        String backupFilePath = backupFolderPath + fileName;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("mysqldump --opt ").append(" --add-drop-database ").append(" --add-drop-table ");
        stringBuilder.append(" -h").append(host).append(" -u").append(userName).append(" -p").append(password).append(" --databases ");
        for (String database : databases) {
            stringBuilder.append(database).append(" ");
        }
        stringBuilder.append(" --result-file=").append(backupFilePath).append(" --default-character-set=utf8 ");
        System.out.println(stringBuilder.toString());
        // 调用外部执行exe文件的 Java Api
        ;
        try {
            Process process = Runtime.getRuntime().exec(getCommand(stringBuilder.toString()));
            if (process.waitFor() == 0) {
                System.out.println("数据已备份到 " + backupFilePath + " 目录中");
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 还原数据库
     *
     * @param restoreFilePath 数据库备份的脚本路径
     * @param host            host地址
     * @param userName        数据库用户名
     * @param password        数据库密码
     * @param databases       需要还原的数据库名称
     * @return
     * @throws Exception
     */
    public static boolean restore(String restoreFilePath, String host, String userName, String password, List<String> databases) throws Exception {
        File restoreFile = new File(restoreFilePath);
        if (restoreFile.isDirectory()) {
            for (File file : restoreFile.listFiles()) {
                if (file.exists() && file.getPath().endsWith(".sql")) {
                    restoreFilePath = file.getAbsolutePath();
                    break;
                }
            }
        }
        List<StringBuilder> stringBuilders = new ArrayList<>();
        for (String database : databases) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("mysql -h").append(host).append(" -u").append(userName).append(" -p").append(password);
            stringBuilder.append(" ").append(database).append(" < ").append(restoreFilePath);
            stringBuilders.add(stringBuilder);
        }
        Process process;
        int size = 0;
        for (StringBuilder stringBuilder : stringBuilders) {
            try {
                process = Runtime.getRuntime().exec(getCommand(stringBuilder.toString()));
                if (process.waitFor() == 0) {
                    size++;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        if (size == stringBuilders.size()) {
            System.out.println("数据已从 " + restoreFilePath + " 导入到数据库中");
            return true;
        }
        return false;
    }

    private static String[] getCommand(String command) {
        String os = System.getProperty("os.name");
        String shell = "/bin/sh";
        if (os.toLowerCase().startsWith("win")) {
            shell = "cmd";
        }
        String[] cmd = {shell, "/c", command};
        return cmd;
    }

    public static void main(String[] args) throws Exception {
        String host = "localhost";
        String userName = "root";
        String password = "root";
        List<String> databases = new ArrayList<>();
        databases.add("scmall_admin");
        databases.add("smartshop_common");

//        System.out.println("开始备份");
//        String backupFolderPath = "d:/dev/";
//        String fileName = "kitty.sql";
//        backup(host, userName, password, backupFolderPath, fileName, databases);
//        System.out.println("备份成功");

        System.out.println("开始还原");
        String restoreFilePath = "d:/dev/kitty.sql";
        restore(restoreFilePath, host, userName, password, databases);
        System.out.println("还原成功");

    }
}
